/**
 * 
 */
package com.thoughtworks.merchantsguide.converter;

import com.thoughtworks.merchantsguide.enumeration.RomanToArabic;
import com.thoughtworks.merchantsguide.exception.UnsupportedNumberException;
import com.thoughtworks.merchantsguide.validator.RomanNumberValidator;

/**
 * This converter is used to convert roman numbers to arabic numbers.
 *
 */
public class RomanToArabicConverter {

	/**
	 * Conversion from Roman to Arabic.
	 * 
	 * @param iRomanNumber
	 * @return
	 * @throws UnsupportedNumberException
	 */
	public long convert(String iRomanNumber) throws UnsupportedNumberException {

		long arabicNumber = 0;
		// Check if the number is a valid roman number or not.
		// If not, then return 0.
		if (new RomanNumberValidator().isValidRomanNumber(iRomanNumber)) {

			long lastDigit = 0;
			for (int index = 0; index < iRomanNumber.length(); index++) {
				long currentValue = RomanToArabic.valueOf(String.valueOf(iRomanNumber.charAt(index))).getValue();
				if (lastDigit != 0 && lastDigit < currentValue) {
					currentValue -= lastDigit;
					arabicNumber -= lastDigit;
					arabicNumber += currentValue;
					lastDigit = currentValue;
				} else {
					lastDigit = currentValue;
					arabicNumber += currentValue;
				}
				lastDigit = currentValue;
			}
		} else {
			throw new UnsupportedNumberException();
		}
		return arabicNumber;
	}
}